package com.lijie.ljblog.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lijie.ljblog.mapper.LjpageWebsitehotMapper;
import com.lijie.ljblog.mapper.LjpageWebsitehotcontenthistoryMapper;
import com.lijie.ljblog.mapper.LjpageWebsitehotcontentlatestMapper;
import com.lijie.ljblog.model.LjpageWebsitehot;
import com.lijie.ljblog.model.LjpageWebsitehotcontenthistory;
import com.lijie.ljblog.model.LjpageWebsitehotcontentlatest;
import com.lijie.ljblog.model.vo.ljpage.LjPageHotWebVO;
import com.lijie.ljblog.model.vo.ljpage.LjpageMoMoYuResultVO;
import com.lijie.ljblog.service.LjpageWebsitehotService;
import com.lijie.ljblog.util.BeanListUtils;
import com.lijie.ljblog.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 热门站点信息;(ljPage_webSiteHot)表服务实现类
 * @author : http://www.chiner.pro
 * @date : 2023-5-15
 */
@Service
@Slf4j
public class LjpageWebsitehotServiceImpl implements LjpageWebsitehotService {
    @Autowired
    private LjpageWebsitehotMapper ljpageWebsitehotMapper;

    @Resource
    RestTemplate restTemplate;
    @Resource
    LjpageWebsitehotcontentlatestMapper websiteLatestMapper;
    @Resource
    LjpageWebsitehotcontenthistoryMapper websiteHistoryMapper;
    @Resource
    RedisUtils redisUtils;
    @Resource
    private LjpageWebsitehotServiceImpl serviceImpl;

    private static final String momoyuUrl="https://momoyu.cc/api/hot/list?id=0";
    /**
     1、查询热门网站库，获取需要抓取的信息

     2、调用接口获取各网站热榜信息

     3、delete热榜最新表。重新新增某网站热榜数据。

     4、全部完成后，将数据插入至历史数据表

     * @return
     */

    @Override
    public Integer hotDailyUpdate()  {



        //查询已配置的热门网站库
        List<LjpageWebsitehot> ljpageWebsitehots = ljpageWebsitehotMapper.selectList(null);

        //todo。先用摸摸鱼的API接口
        // List<LjpageWebsitehotcontentlatest> topHubVOList = getTopHubListVO(ljpageWebsitehots);
        //调用摸摸鱼的API
        List<LjpageWebsitehotcontentlatest> topHubVOList = getTopHubMoMoYuListVO(ljpageWebsitehots);

        serviceImpl.updateTopHub(topHubVOList);
        List<LjpageWebsitehotcontenthistory> ljpageWebsitehotcontenthistories = BeanListUtils.copyListProperties(topHubVOList, LjpageWebsitehotcontenthistory::new);
        websiteHistoryMapper.insertBatch(ljpageWebsitehotcontenthistories);

        log.info("各网站热榜更新了"+topHubVOList.size()+"条数据");

        //清除redis数据
        redisUtils.delete("ljPage:hot::hotList");

        log.info("清除缓存成功");
        return topHubVOList.size();

    }

    @Override
    @Cacheable(cacheNames = "ljPage:hot", key = "T(String).valueOf('hotList')" )
    public List<LjPageHotWebVO> hotList() {
        log.info("缓存过期，查询热榜数据");
        return websiteLatestMapper.hotList();
    }

    /**
     *
     *  调用摸摸鱼接口，获取热门网站的接口
     * @param ljpageWebsitehots
     * @return
     */
    private List<LjpageWebsitehotcontentlatest> getTopHubMoMoYuListVO(List<LjpageWebsitehot> ljpageWebsitehots){

        List<LjpageWebsitehotcontentlatest> resultList = new ArrayList<>();

        //调用接口
        ResponseEntity<String> forEntity = restTemplate.getForEntity(momoyuUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(forEntity.getBody());
        JSONArray hubJsonArray  = jsonObject.getJSONArray("data");
        List<LjpageMoMoYuResultVO> moMoYuResultVOList = JSON.parseArray(hubJsonArray.toJSONString(), LjpageMoMoYuResultVO.class);

        if(CollUtil.isEmpty(moMoYuResultVOList)) return resultList;

        Map<String, LjpageWebsitehot> collectMap = ljpageWebsitehots
                .stream()
                .filter(e -> e.getWebKey() != null)
                .collect(Collectors.toMap(LjpageWebsitehot::getWebKey, e -> e));

        for (LjpageMoMoYuResultVO moMoYuResultVO:moMoYuResultVOList) {
            List<LjpageWebsitehotcontentlatest> data = moMoYuResultVO.getData();
            LjpageWebsitehot ljpageWebsitehot = collectMap.get(moMoYuResultVO.getSource_key());
            if(ljpageWebsitehot!=null){
                for (int i=0;i<data.size();i++) {
                    LjpageWebsitehotcontentlatest datum = data.get(i);
                    datum.setId(null);
                    datum.setRank(i+1);
                    datum.setWebId(ljpageWebsitehot.getId());
                }

                resultList.addAll(data);
            }

        }

        return resultList;

    }

    /**
     *
     *  获取各个网站的热榜数据
     * @param ljpageWebsitehots
     * @return
     */
    //todo 带改造，等今日热榜API申请下来后修改
    private List<LjpageWebsitehotcontentlatest> getTopHubListVO(List<LjpageWebsitehot> ljpageWebsitehots){

        List<LjpageWebsitehotcontentlatest> resultList = new ArrayList<>();

        for (LjpageWebsitehot ljpageWebsitehot : ljpageWebsitehots) {
            try {
                Thread.sleep(200);
            }catch (InterruptedException e ){
                log.error(e.getMessage());
            }

            ResponseEntity<String> forEntity = restTemplate.getForEntity(ljpageWebsitehot.getWebhoturl(), String.class);
            JSONObject jsonObject = JSON.parseObject(forEntity.getBody());
            log.info(String.valueOf(jsonObject.get("Code"))+String.valueOf(jsonObject.get("Message")));
            JSONArray hubJsonArray  = ((JSONObject) jsonObject.get("Data")).getJSONArray("data");

            List<LjpageWebsitehotcontentlatest> ljpageList = JSON.parseArray(hubJsonArray.toJSONString(), LjpageWebsitehotcontentlatest.class);
            if(CollUtil.isEmpty(ljpageList)){
                return resultList;
            }
            for (int i =1 ;i<=ljpageList.size();i++) {
                LjpageWebsitehotcontentlatest ljpageWebsitehotcontentlatest = ljpageList.get(i - 1);
                ljpageWebsitehotcontentlatest.setWebId(ljpageWebsitehot.getId());
                ljpageWebsitehotcontentlatest.setRank(i);
                ljpageWebsitehotcontentlatest.setTitle(ljpageWebsitehotcontentlatest.getTitle());
                ljpageWebsitehotcontentlatest.setId(null);
            }
            resultList.addAll(ljpageList);

        }
        return resultList;

    }

    /**
     *  delete热榜最新表。重新新增某网站热榜数据。
     * @param list
     */
    @Transactional
    public void  updateTopHub( List<LjpageWebsitehotcontentlatest> list){
        websiteLatestMapper.delete(null);
        websiteLatestMapper.insertBatch(list);
    }
}